const playerDirector = (() => {
    let players = {}; // 保存所有玩家
    let operations = {}; // 中介者可执行的操作

    operations.addPlayer = (player) => {
        let teamColor = player.teamColor;
        players[teamColor] = players[teamColor] || []; // 建立队伍
        players[teamColor].push(player); // 添加玩家进队伍
    }

    operations.removePlayer = (player) => {
        let teamColor = player.teamColor;
        teamPlayers = players[teamColor] || [];

        for (let i in teamPlayers) {
            if (teamPlayers[i] === player) {
                teamPlayers.splice(i, 1);
                break;
            }
        }
    }

    operations.changeTeam = (player, newTeamColor) => {
        operations.removePlayer(player);
        player.teamColor = newTeamColor;
        operations.addPlayer(player);
    }

    operations.playerDead = (player) => {
        let teamColor = player.teamColor;
        let teamPlayers = players[teamColor]; // 玩家所在队伍
        let all_dead = true;

        for (let player of teamPlayers) {
            if (player.state !== 'dead') {
                all_dead = false;
                return;
            }
        }

        if (all_dead === true) {
            teamPlayers.forEach(x => x.lose()); // 本队所有玩家 lose 
            for (let color in players) {
                if (color !== teamColor) {
                    let teamPlayers = players[color]; // 其他队伍的玩家
                    teamPlayers.forEach(x => x.win()); // 其他队伍所有玩家 win
                }
            }
        }
    }

    const reciveMessage = (...args) => {
        let message = args.shift();
        operations[message](...args);
    }

    return {
        reciveMessage
    }
})();

class Player {
    constructor(name, teamColor) {
        this.name = name;
        this.teamColor = teamColor;
        this.state = 'alive'; // 玩家生存状态
    }

    win() {
        console.log(this.name + 'won');
    }

    lose() {
        console.log(this.name + 'lost');
    }

    die() {
        this.state = 'dead';
        playerDirector.reciveMessage('playerDead', this); // 向中介者发送消息，玩家死亡
    }

    remove() {
        playerDirector.reciveMessage('removePlayer', this); // 向中介者发送消息，移除一个玩家
    }

    changeTeam(color) {
        playerDirector.reciveMessage('changeTeam', this, color); // 向中介者发送消息，玩家换队
    }
}

function playerFactory(name, teamColor) {
    let newPlayer = new Player(name, teamColor);
    playerDirector.reciveMessage('addPlayer', newPlayer);
    return newPlayer;
}

// test
// 红队：
let player1 = playerFactory('皮蛋', 'red'),
    player2 = playerFactory('小乖', 'red'),
    player3 = playerFactory('宝宝', 'red'),
    player4 = playerFactory('小强', 'red');
// 蓝队：
let player5 = playerFactory('黑妞', 'blue'),
    player6 = playerFactory('葱头', 'blue'),
    player7 = playerFactory('胖墩', 'blue'),
    player8 = playerFactory('海盗', 'blue');

player1.changeTeam('blue');
player2.die();
player3.die();
player4.die();
